package com.common.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.constant.GoodsConstant;
import com.common.constant.SystemConstants;
import com.common.domain.entity.*;
import com.common.domain.vo.LeaveInfoVo;
import com.common.domain.vo.VolunteerLogVo;
import com.common.domain.vo.VolunteerVo;
import com.common.enums.AppHttpCodeEnum;
import com.common.mapper.PointMapper;
import com.common.mapper.VisitRecordMapper;
import com.common.mapper.VolunteerLogMapper;
import com.common.mapper.VolunteerMapper;
import com.common.service.VisitRecordService;
import com.common.service.VolunteerService;
import com.common.util.RedisCache;
import com.common.util.SecurityUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
* @author pc
* @description 针对表【sys_visit_record】的数据库操作Service实现
* @createDate 2023-11-02 21:08:46
*/
@Service
public class VolunteerServiceImpl extends ServiceImpl<VolunteerMapper, Volunteer>
implements VolunteerService {
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private VolunteerMapper volunteerMapper;

    @Autowired
    private VolunteerLogMapper volunteerLogMapper;

    @Autowired
    private PointMapper pointMapper;
    @Override
    public ResponseResult allVolunteerList(Integer pageNum, Integer pageSize,
                                           String name, Long userId) {
        PageHelper.startPage(pageNum,pageSize);

        List<VolunteerVo> list = volunteerMapper.allVolunteerList(name, userId);
        PageInfo<VolunteerVo> pageInfo = new PageInfo<>(list);

        pageInfo.setList(list);

        return ResponseResult.okResult(pageInfo);
    }

    @Override
    public ResponseResult deleteVolunteer(String ids) {
        String[] split = ids.split(",");
        removeByIds(Arrays.asList(split));
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult insertGoods(Volunteer volunteer) {
        save(volunteer);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult updateVolunteer(Volunteer volunteer) {
        updateById(volunteer);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult allVolunteerLogList(Integer pageNum, Integer pageSize, Long id, String userName) {
        PageHelper.startPage(pageNum,pageSize);

        List<VolunteerLogVo> list = volunteerMapper.allVolunteerLogList(id, userName, null);
        PageInfo<VolunteerLogVo> pageInfo = new PageInfo<>(list);

        pageInfo.setList(list);

        return ResponseResult.okResult(pageInfo);
    }

    @Override
    public ResponseResult updateVolunteerLog(String ids) {
        String[] split = ids.split(",");
        LambdaQueryWrapper<VolunteerLog> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(VolunteerLog::getId,Arrays.asList(split));
        VolunteerLog volunteerLog = new VolunteerLog();
        volunteerLog.setStatus(SystemConstants.PARTICIPATION_FLAG);
        volunteerLogMapper.update(volunteerLog,queryWrapper);

        //批量赠送积分
        for (int i = 0; i < split.length; i++) {
            //查询用户ID和活动信息
            VolunteerLog volunteerLog1 = volunteerLogMapper.selectById(ids);
            Long volunteerId = volunteerLog1.getVolunteerId();
            Long userId = volunteerLog1.getUserId();
            Volunteer volunteer = volunteerMapper.selectById(volunteerId);
            Point point = new Point();
            point.setUserId(userId);
            point.setScore(Long.valueOf(volunteer.getPoint()));
            point.setScoreDetail("参与"+volunteer.getVolunteerName()+"获得");
            point.setType(GoodsConstant.ADD_POINT);
            pointMapper.insert(point);
        }
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult application(Long volunteerId) {
        //校验是否有其他请求
        String userKey = SecurityUtils.getUserId() + "_application";
        if(redisCache.exists(userKey)){
            return new ResponseResult().ok(AppHttpCodeEnum.OTHER_REQUESTS_ERROR);
        }
        Volunteer volunteer = volunteerMapper.selectById(volunteerId);
        if(volunteer == null){
            return new ResponseResult().ok(AppHttpCodeEnum.VOLUNTEER_ERROR);
        }

        try {
            //添加请求
            redisCache.set(userKey, 1, 10L);
            String volunteerKey = volunteerId + "_count";
            Long count = 0L;
            if(redisCache.exists(volunteerKey)){
                count = volunteer.getNumber() - Long.parseLong(redisCache.getCacheObject(volunteerKey).toString());
            }else{
                LambdaQueryWrapper<VolunteerLog> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(VolunteerLog::getVolunteerId, volunteerId);
                Integer integer = volunteerLogMapper.selectCount(queryWrapper);
                redisCache.set(volunteerKey, Long.valueOf(integer), 600L);
                count = volunteer.getNumber() - Long.valueOf(integer);
            }
            //获取商品剩余数量
            if(count < 0){
                return new ResponseResult().error(-102,AppHttpCodeEnum.VOLUNTEER_NUMBER_ERROR.getMsg());
            }
            //添加报名纪录
            VolunteerLog volunteerLog = new VolunteerLog();
            volunteerLog.setVolunteerId(volunteerId);
            volunteerLog.setUserId(SecurityUtils.getUserId());

            volunteerLogMapper.insert(volunteerLog);
            //添加
            redisCache.incrBy(volunteerKey);
            return new ResponseResult().ok("报名成功");
        }catch (Exception e){
            //删除缓存
            return new ResponseResult().ok("报名失败，请稍后再试");
        }finally {
            //删除缓存
            redisCache.remove(userKey);
        }
    }

    @Override
    public ResponseResult allVolunteerLogList(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);

        List<VolunteerLogVo> list = volunteerMapper.allVolunteerLogList(null, null, SecurityUtils.getUserId());
        PageInfo<VolunteerLogVo> pageInfo = new PageInfo<>(list);

        pageInfo.setList(list);

        return ResponseResult.okResult(pageInfo);
    }
}
